<?php
/**
 * 在线用户模型类
 * ===============================================
 * @copyright 深圳市顶速网络科技有限公司  http://fasttop.top
 * ===============================================
 * @author: Ketity <970564173@qq.com>
 * @date: 2015-6-16
 */
namespace Common\Model;
class UserOnlineModel extends \Think\Model {
	
	protected $_validate = array ();
	protected $_auto = array ();
	
	/**
	 * 初始化
	 * @see Think.Model::_initialize()
	 */
	public function _initialize() {
	
	}
	
	/**
	 * 新增在线用户
	 * @param int $roomid
	 * @param array $userOnlineInfo
	 * @param string $offline_time
	 */
	public function addUserOnline($roomid, $userOnlineInfo, $offline_time) {
		if (empty ( $roomid ) || empty ( $userOnlineInfo ) || empty ( $offline_time )) {
			$this->error = L ( 'error_parameter' );
			return false;
		}
		$userOnlineInfo ['roomid'] = $roomid;
		$data = $this->create ( $userOnlineInfo );
		if ($data) {
			$result = $this->add ( $data );
			$this->deleteUserOnline ( $roomid, $offline_time );
			return $result ? $result : 0;
		}
		return $this->getError ();
	}
	
	/**
	 * 更新在线用户信息
	 * @param string $user_online_id
	 * @param int $roomid
	 * @param string $offline_time
	 */
	public function editUserOnline($user_online_id, $roomid, $offline_time) {
		if (empty ( $user_online_id ) || empty ( $roomid ) || empty ( $offline_time )) {
			$this->error = L ( 'error_parameter' );
			return false;
		}
		$data ['createtime'] = NOW_TIME;
		$result = $this->where ( 'user_online_id="' . $user_online_id . '"' )->save ( $data );
		if ($result) {
			$this->deleteUserOnline ( $roomid, $offline_time );
			return $result;
		}
		return $this->getError ();
	}
	
	/**
	 * 删除用户离线时间大于系统规定离线时间的用户，例：系统规定离线时间为20秒，则用户离线时间超过20秒的用户即会被删除
	 * @param int $roomid
	 * @param string $offline_time
	 */
	protected function deleteUserOnline($roomid, $offline_time) {
		$where ['roomid'] = $roomid;
		$where ['createtime'] = array ('lt', NOW_TIME - $offline_time );
		return $this->where ( $where )->delete ();
	}
	
	/**
	 * 获取在线用户列表
	 * @param int $roomid
	 * @param string $offline_time
	 */
	public function getUserOnline($roomid, $offline_time) {
		if (empty ( $roomid ) || empty ( $offline_time )) {
			$this->error = L ( 'error_parameter' );
			return false;
		}
		$where ['roomid'] = $roomid;
		$where ['createtime'] = array ('egt', NOW_TIME - $offline_time );
		$userData = $this->where ( $where )->order ( 'role desc' )->select ();
		return $userData;
	}
	
	/**
	 * 根据用户ID和聊天室ID
	 * @param unknown_type $user_online_id
	 * @param unknown_type $roomid
	 */
	public function getUser($user_online_id, $roomid) {
		if (empty ( $user_online_id ) || empty ( $roomid )) {
			$this->error = L ( 'error_parameter' );
			return false;
		}
		$where ['roomid'] = $roomid;
		$where ['user_online_id'] = $user_online_id;
		$user = $this->where ( $where )->find ();
		return $user;
	}
}